package controller;

import model.Blog;
import model.BlogDAO;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Creat with IntelliJ IDEA
 * Description:
 * User:WZW
 * Date:2022-08-07
 * Time:23:10
 */
@WebServlet("/blogDelete")
public class BlogDeleteServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 检查当前用户是否登录
        HttpSession session = req.getSession(false);
        if (session == null) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("当前尚未登录，不具备删除权限！");
            return;
        }
        User user = (User) session.getAttribute("user");
        if (user == null) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("当前尚未登录，不具备删除权限！");
            return;
        }

        // 2. 获取当前blogId
        String blogId = req.getParameter("blogId");
        if (blogId == null || "".equals(blogId)) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("当前参数不对！");
            return;
        }
        // 3. 获取要删除的博客信息
        BlogDAO blogDAO = new BlogDAO();
        Blog blog = blogDAO.selectOne(Integer.parseInt(blogId));
        if (blog == null) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("当前要删除的博客不存在！");
            return;
        }

        // 4. 再次检验，当前的用户是否是博客的作者
        if (user.getUserId() == blog.getUserId()) {
            // 5. 删除博客
            blogDAO.delete(Integer.parseInt(blogId));
            // 6. 跳转到博客列表页
            resp.sendRedirect("blog_list.html");
        } else {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("当前用户不具备删除权限！");
            return;
        }
    }
}
